<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller;

use library\Controller;
use library\tools\Data;
use think\Db;
use think\facade\Config;
// use think\Config;
/*工具类*/
use redis\Redis;
use think\facade\Log;
/**
 * 系统用户管理
 * Class User
 * @package app\admin\controller
 */
class User extends Controller
{


    /**
     * 指定当前数据表
     * @var string
     */
    public $table = 'SystemUser';

    /**
     * 系统用户管理
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        $this->title = '系统用户管理';
        $query = $this->_query($this->table)->like('username,phone,mail')->equal('status');
        $query->dateBetween('login_at,create_at')->where(['is_deleted' => '0'])->order('id desc')->page();
    }

    /**
     * 添加系统用户
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {

        $dbconf = $this->getconfig('vister_db');
        $data = Db::connect($dbconf)->table('role')->select();
        $fk_role = [
            'id' => 0,
            'name' => '访客',
            'actions' => '',
            'fields' => '',
            'createtime' => time(),
        ];
        array_push($data, $fk_role);
        $this->assign('role',$data);
        $this->applyCsrfToken();
        $this->_form($this->table, 'form');

    }

    /**
     * 同步用户
     * @HtttpRequest                          get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-08-20T17:30:17+0800
     * @LastTime     2020-08-20T17:30:17+0800
     * @return       [type]                   [description]
     */
    public function sync(){
       /*同步用户*/
        $dbconf = $this->getconfig('vister_db');
        $res = Db::connect($dbconf)->table('view_user')->select();
        $countinsert = 0;
        foreach ($res as $key => $value) {
            # code...
            $check = Db::table('view_system_user')->where('openid = "'.$value['openid'].'"')->find();
            if($check==NULL){
                $data = [
                    'username' => $value['name']?:'',
                    'password' => $value['password'],
                    'openid' =>   $value['openid'],
                    'phone' =>    $value['mobile'],
                    'desc' => '同步',
                    'status' => 1,
                    'create_at' => date('Y-m-d H:i:s', time()),
                    'roleid' => $value['roleid'],
                    'companyid' => $value['companyid'],
                ];
                switch ($value['roleid']) {
                    case '1':
                        # code...
                        Log::info('系统管理员同步-请手动同步'.$value['id']);
                        break;
                    case '2':
                        $data['authorize'] = 2;
                        # code...
                        break; 
                    case '3':
                    case '4':
                        $data['authorize'] = 4;
                        # code...
                        break;
                    case '5':
                        $data['authorize'] = 5;
                    case '6':
                        $data['authorize'] = 6;
                    case '8':
                        $data['authorize'] = 8;
                    case '0':
                    case '9':
                        # code...
                        $data['authorize'] = 9;
                        # code...
                        break;
                    default:
                        $data['authorize'] = 9;
                        # code...
                        break;
                }
                if($value['name']!=NULL){
                    $result = Db::name('system_user')->insert($data);
                    $countinsert++;
                    echo '<div style="text-align: center;">成功同步-'.$value['name'].'用户</div></br>';
                }

            }else{
                //更新用户信息
                $data = [
                    'username' => $value['name']?:'',
                    'password' => $value['password'],
                    'openid' =>   $value['openid'],
                    'phone' =>    $value['mobile'],
                    'desc' => '同步更新',
                    'status' => 1,
                    'create_at' => date('Y-m-d H:i:s', time()),
                    'roleid' => $value['roleid'],
                    'companyid' => $value['companyid'],
                ];
                switch ($value['roleid']) {
                    case '1':
                        # code...
                        Log::info('系统管理员同步-请手动同步'.$value['id']);
                        break;
                    case '2':
                        $data['authorize'] = 2;
                        # code...
                        break; 
                    case '3':
                    case '4':
                        $data['authorize'] = 4;
                        # code...
                        break;
                    case '5':
                        $data['authorize'] = 5;
                    case '6':
                        $data['authorize'] = 6;
                    case '8':
                        $data['authorize'] = 8;
                    case '0':
                    case '9':
                        # code...
                        $data['authorize'] = 9;
                        # code...
                        break;
                    default:
                        $data['authorize'] = 9;
                        break;
                }
                if($value['name']!=NULL){
                    $result = Db::name('system_user')->where('id = '.$check['id'])->data($data)->update();
                    $countinsert++;
                    echo '<div style="text-align: center;">成功同步-'.$value['name'].'用户</div></br>';
                }
            }

        }

        echo '<div style="text-align: center;">同步完成--一共同步:'.$countinsert.'位用户</div>';
    }

    /**
     * 编辑系统用户
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit()
    {

        $dbconf = $this->getconfig('vister_db');
        $data = Db::connect($dbconf)->table('role')->select();
        $fk_role = [
            'id' => 0,
            'name' => '访客',
            'actions' => '',
            'fields' => '',
            'createtime' => time(),
        ];
        array_push($data, $fk_role);
        $this->assign('role',$data);
        $this->applyCsrfToken();
        if($this->request->isPost()){
            $phone = $this->request->param('phone');
            $mail = $this->request->param('mail');
            $roleid = $this->request->param('roleid');

            $find_db1 = Db::connect($dbconf)->table('view_user')->where(['mobile' => $phone])->order('createtime desc')->find();
            if($find_db1){
                $data = [
                    'mobile' => $phone,
                    'roleid' => $roleid,
                    'email' => $mail,
                ];
                $res = Db::connect($dbconf)->table('user')->where(['id' => $find_db1['id']])->data($data)->update();
            }
            $this->_form($this->table, 'form');
            //$this->success('更新用户信息成功');
        }

        $this->_form($this->table, 'form');
    }

    /**
     * 修改用户密码
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function pass()
    {
        $redis = new Redis;
        $this->applyCsrfToken();
        if ($this->request->isGet()) {
            $this->verify = false;
            $this->_form($this->table, 'pass');
        } else {
            $post = $this->request->post();
            if ($post['password'] !== $post['repassword']) {
                $this->error('两次输入的密码不一致！');
            }
            //加入验证码 验证
            //
            // $verify_code = $redis::get('pc_phone_Message_chpassword_'.$userinfo['db1']['id']);
            // if(!$verify_code){$this->error('验证码过时,请重新发送');}
            // if($this->request->param('yz_code') != $verify_code){$this->error('验证码错误');}

            if (Data::save($this->table, ['id' => $post['id'], 'password' => md5($post['password'].Config::get('salt'))], 'id')) {

                $this->success('密码修改成功，下次请使用新密码登录！', '');
            } else {
                $this->error('密码修改失败，请稍候再试！');
            }
        }
    }

    /**
     * 表单数据处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _form_filter(&$data)
    {
        if ($this->request->isPost()) {
            // 用户权限处理
            $data['authorize'] = (isset($data['authorize']) && is_array($data['authorize'])) ? join(',', $data['authorize']) : '';
            // 用户账号重复检查
            if (isset($data['id'])) unset($data['username']);
            elseif (Db::name($this->table)->where(['username' => $data['username'], 'is_deleted' => '0'])->count() > 0) {
                $this->error("账号{$data['username']}已经存在，请使用其它账号！");
            }
        } else {
            $data['authorize'] = explode(',', isset($data['authorize']) ? $data['authorize'] : '');
            $this->authorizes = Db::name('SystemAuth')->where(['status' => '1'])->order('sort desc,id desc')->select();


        }
    }
    /**
     * 禁用系统用户
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbid()
    {
        if (in_array('10000', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止操作！');
        }
        $this->applyCsrfToken();
        $this->_save($this->table, ['status' => '0']);
    }

    /**
     * 启用系统用户
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        $this->applyCsrfToken();
        $this->_save($this->table, ['status' => '1']);
    }

    /**
     * 删除系统用户
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {
        $dbconf = $this->getconfig('vister_db');
        $uid  =  $this->request->post('id');
        if (in_array('10000', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止删除！');
        }
        $this->applyCsrfToken();
        
        $now_userinfo = Db::table('system_user')->where('id = '.$uid)->find();
        //同时删除用户相关信息  包括dev数据库
        $where = 'openid = "'.$now_userinfo['openid'].'"';
        $dev_userinfo = Db::connect($dbconf)->table('view_user')->where('openid = "'.$now_userinfo['openid'].'"')->find();
        //会员信息
        $where = 'openid = "'.$dev_userinfo['openid'].'"';
        $find_user_member = Db::connect($dbconf)->table('view_user_store_member')->where('openid = "'.$dev_userinfo['openid'].'"')->find();
        if($find_user_member){
            $res = Db::connect($dbconf)->table('store_member')->where('id = '.$find_user_member['id'])->useSoftDelete('deletetime',time())->delete();
        }
        //公司
        $find_company = Db::connect($dbconf)->table('view_company')->where('createuid = '.$dev_userinfo['id'])->find();
        if($find_company){
            $res = Db::connect($dbconf)->table('company')->where('id = '.$find_company['id'])->data(['createuid'=>NULL,'status'=>0])->update();
            $res = Db::connect($dbconf)->table('dept')->where('companyid = '.$find_company['id'])->data(['status'=>0])->update();
        }
        //订单购买记录
        $res =  Db::connect($dbconf)->table('commodity_orders')->where('id = '.$dev_userinfo['id'])->useSoftDelete('deletetime',time())->delete();

        //先删除用户信息 - 最后删除用户
        $res = Db::connect($dbconf)->table('user')->where('id = '.$dev_userinfo['id'])->useSoftDelete('deleteTime',time())->delete();
        $this->_delete($this->table);
    }


    //上传身份证验证(仅扫描)
    public function upload_postidcard(){
        $file = $this->request->file('imgurl');
        $type = $this->request->param('type'); /*修改信息身份证-----chidcard*/
        $uptype = $this->request->param('uptype'); /*file url*/
        $url = $this->request->param('url'); 
        $image_type = $this->request->param('image_type')?:'front'; //back front

        if($uptype=='url'){
            try{
                $ai = new \Baidu_AI();
                $res = $ai->identitycard_verify($url,$image_type);
// array(4) { ["words_result"]=> array(3) { ["失效日期"]=> array(2) { ["words"]=> string(8) "20280227" ["location"]=> array(4) { ["top"]=> int(1091) ["left"]=> int(125) ["width"]=> int(58) ["height"]=> int(318) } } ["签发机关"]=> array(2) { ["words"]=> string(18) "中山市公安局" ["location"]=> array(4) { ["top"]=> int(744) ["left"]=> int(262) ["width"]=> int(58) ["height"]=> int(360) } } ["签发日期"]=> array(2) { ["words"]=> string(8) "20180227" ["location"]=> array(4) { ["top"]=> int(738) ["left"]=> int(121) ["width"]=> int(58) ["height"]=> int(303) } } } ["log_id"]=> int(1331951291882012673) ["words_result_num"]=> int(3) ["image_status"]=> string(6) "normal" }
                if($image_type=='front'){
                    $name = $res['words_result']['姓名']['words'];
                    $sex = $res['words_result']['性别']['words'];
                    $address = $res['words_result']['住址']['words'];
                    $identitycard = $res['words_result']['公民身份号码']['words'];
                    $birth = $res['words_result']['出生']['words'];
                    $brithday   = substr($birth,0,4)."-".substr($birth,4,2)."-".substr($birth,6,2);
                    /*民族*/
                    $mz = $res['words_result']['民族']['words'];
                    $data = ['type'=>'front','name'=>$name,'sex'=>$sex,'address'=>$address,'birth'=>$brithday,'identitycard'=>$identitycard,'src'=>$url];
                }
                
                if($image_type=='back'){
                    $get_date = $res['words_result']['签发日期']['words'];
                    $lost_date = $res['words_result']['失效日期']['words'];
                    $ca = $res['words_result']['签发机关']['words'];
                    $data = ['type'=>'back','get_date'=>$get_date,'lost_date'=>$lost_date,'ca'=>$ca,'src'=>$url];
                }


            }catch(\Throwable $th){
                $this->error('身份证识别失败,请重新上传',[],400);
            }

                $this->success('身份证验证成功',$data,200);
                //return toJson(['message'=>'','code'=>'200','data'=>$data,'src'=>$url]); 
        }

        $info = $file->validate(['ext'=>'jpg,jpeg,png'])
                     ->move(Config::get('upload_identitycard_path'));
        if($info){
            $ai = new \Baidu_AI();
            if($info->getSize() > 700000){
                $source = Config::get('upload_identitycard_path') . $info->getSaveName();
                $path = Config::get('upload_identitycard_thumb_path').'/'.date('Ymd');
                if(!file_exists($path)){
                    mkdir($path,0777,true);
                }
                $image_name = md5(time().$source);
                $dst_img = $path.'/'.$image_name.'.jpg';
                $percent = 0.1;  #原图压缩，不缩放，但体积大大降低
                $image = (new Compress($source,$percent))->compressImg($dst_img);
                $res = $ai->identitycard_verify($dst_img);
            }else{
                $res = $ai->identitycard_verify(Config::get('upload_identitycard_path') . $info->getSaveName());
            }
            
            if($res['idcard_number_type'] == 1 ){   
                $name = $res['words_result']['姓名']['words'];
                $sex = $res['words_result']['性别']['words'];
                $address = $res['words_result']['住址']['words'];
                $identitycard = $res['words_result']['公民身份号码']['words'];
                $data = ['name'=>$name,'sex'=>$sex,'address'=>$address,'identitycard'=>$identitycard];

                /*此处修改身份证信息 更新*/
                if($type == 'chidcard'){
                    #code ......
                     #
                }
                $data = ['message'=>'身份证验证成功','code'=>'200','data'=>$data,'src'=>$info->getSaveName()];
                $this->success('身份证验证成功',$data,200);
                //return toJson();
            }else{
                $this->error('请上传正确的身份证',[],400);
                //return toJson(['message'=>'请上传正确的身份证','code'=>'400']);
            }
        }else{
            // 返回失败获取错误信息
            $this->error('身份证识别失败',[],400);
            //return toJson(['message'=>$file->getError(),'code'=>'400']);
        }
    }

}
